import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { STColumn } from '@delon/abc/st';
import { toDate } from '@delon/util';
import { FilterGroup, FilterOperate, FilterRule, PageRequest } from '@shared/itcore/itcore.model';
import { AlainService } from '@shared/itcore/services/alain.service';
import { itcoreService } from '@shared/itcore/services/itcore.service';
import { List } from 'linqts';

import { AdSearchModalComponent } from './modal/modal.component';

@Component({
  selector: 'itcore-ad-search',
  templateUrl: './ad-search.component.html',
  styles: [],
})
export class AdSearchComponent implements OnInit {
  @Input() request: PageRequest;
  @Input() columns: STColumn[];

  @Input() fieldWidth: number;

  @Output() submited: EventEmitter<PageRequest> = new EventEmitter<PageRequest>();
  @ViewChild('searchModal', { static: false }) searchModal: AdSearchModalComponent;

  rule: FilterRule;

  constructor(private itcore: itcoreService, private alain: AlainService) {
    this.rule = new FilterRule(null, null);
    this.rule.control = 'string';
  }

  ngOnInit() {
    this.columns = new List(this.columns)
      .Where(m => m.index && m.filterable) // TODO: date 的UI未调好，暂不过滤
      .ToArray();
  }

  fieldChange(field: string) {
    const column = this.columns.find(m => m.index === field);
    if (!column) {
      this.itcore.warning(`指定属性${field}不存在`);
      return;
    }
    this.alain.changeFilterRuleType(this.rule, column);
  }

  search() {
    if (!this.rule.Field) {
      this.itcore.warning('请选择要查询的列');
      return;
    }
    const rule = new FilterRule(this.rule.Field, this.rule.Value);
    rule.Operate =
      this.rule.control === 'string'
        ? FilterOperate.Contains
        : FilterOperate.Equal;

    const group = new FilterGroup();

    // 添加时间过滤 start
    if (this.rule.control === 'date') {
      group.Rules.push(
        new FilterRule(this.rule.Field, this.itcore.dateFtt(this.rule.Value[0]), FilterOperate.GreaterOrEqual));
      group.Rules.push(
        new FilterRule(this.rule.Field, this.itcore.dateFtt(this.rule.Value[1]), FilterOperate.LessOrEqual));

    } else {
      group.Rules.push(rule);
    }
    // 添加时间过滤 end

    this.request.FilterGroup = group;
    if (this.submited) {
      this.submited.emit(this.request);
    }
  }

  adSearch() {
    if (this.searchModal) {
      this.searchModal.open();
    }
  }

  adSearchSubmited(request: PageRequest) {
    if (this.submited) {
      this.submited.emit(request);
    }
  }

  reset() {
    this.rule = new FilterRule(null, null);
    if (this.searchModal) {
      this.searchModal.reset();
    }
  }
}
